import React, { Component } from 'react'
import { Input,Button,message,Modal,Upload, Icon } from 'antd';
import './AddNews.less'
import 'react-quill/dist/quill.snow.css';
import {addNews} from '../../../redux/action/admin/adminNews'
import ReactQuill,{Quill} from 'react-quill'
import { connect } from 'react-redux'
import axios from 'axios'


export class AddNews extends Component {
    constructor(props) {
        super(props)
        this.state = { 
            text: '' ,
            title: React.createRef(),
            picModal: false,
            loading: false,
            picUrl: '',
        } 
    }
    /**
     * 文本框输入内容回调
     */
    handleText = (value) => {
        this.setState({
             text: value
         })
    }
 /**
  * 上传前图片格式限制
  * @param  file 
  */ 
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
        if (!isJpgOrPng) {
        message.error('抱歉你只能上传jpg,png或jpeg格式的图片!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
        message.error('图片必须小于2MB!');
        }
        return isJpgOrPng && isLt2M;
    }
    /**
     * 上传图片
     */
    uploadPic = async(info) => {
            const formData = new FormData();
            formData.append('newsPic', info.file);
            const data = (await axios({
              url: 'http://47.107.174.79:8088/api/upload.do',
              method: 'post',
              processData: false,
              data: formData,
            })).data.data[0]
            this.setState({
                picUrl: data
            })
    }
    /**
     * 添加新闻
     */
    addNews = () =>{
        if(this.state.text === ''){
            message.error('新闻内容不能为空！')
            return
        }
        if(this.state.title.current.state.value === undefined){
            message.error('新闻标题不能为空！')
            return
        }
        this.props.dispatch(addNews({news:{
            title: this.state.title.current.state.value,
            content: this.state.text
        }})).then(() => {
            if(this.props.addNews.addNews.code === 'SUCCESS'){
                message.success('添加新闻成功')
                setTimeout(window.location.href='http://localhost:8081/admin/news',1);
            }
        })
    }
    /**
     * 显示图片上传框
     */
    showModal = () => {
        this.setState({
          picModal: true,
        });
    };
    /**
     * 点击确认插入图片
     */
    handleOk = e => {
        let text = this.state.text + ` <img src='${this.state.picUrl}' alt="pic" style={{ width: '100%' }} />`
        this.setState({
          picModal: false,
          text: text
        });
    };
    /**
     * 关闭图片上传框
     */
    handleCancel = e => {
        this.setState({
          picModal: false,
        });
    };



    render() {
        /**markdown文本编辑器工具栏配置 */
        const toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],
 
            [{ 'header': 1 }, { 'header': 2 }],               // custom button values
            [{ 'list': 'ordered'}, { 'list': 'bullet' }],
            [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
            [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
            [{ 'direction': 'rtl' }],                         // text direction
 
            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
 
            [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['link', 'image', 'video'],
            ['clean']                                         // remove formatting button
        ];
        const modules = {
            toolbar: {
                container: toolbarOptions,
                handlers: {
                    'image':this.showModal
                }
            },
        }
        /**
         * 图片预览
         */
        const uploadButton = (
            <div>
              <Icon type={this.state.loading ? 'loading' : 'plus'} />
              <div className="ant-upload-text">Upload</div>
            </div>
          );

        return (
            <div className='add-news'>
                <div className='add-news-header'>
                <Input style={{width:200,marginTop:5,marginRight:10,marginBottom:20}} placeholder="请输入新闻的标题" ref={this.state.title}/>
                <Button type="primary" style={{background:'green'}} onClick={this.addNews}>添加新闻</Button>
                <span style={{paddingLeft:'40%',color:"red"}}>温馨提示：单次新闻编辑请不要上传超过2M的图片</span>
                </div>
                <div className='add-news-content'>
                    <ReactQuill theme="snow" value={this.state.text} onChange={this.handleText} modules={modules}/>
                    <Modal
                        title="添加图片"
                        visible={this.state.picModal}
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                        okText = '确认'
                        cancelText = '取消'
                        >
                            <Upload
                                name="file"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="http://47.107.174.79:8088/api/upload.do"
                                customRequest = {this.uploadPic}
                                beforeUpload={this.beforeUpload}
                            >
                                {this.state.picUrl ? <img src={this.state.picUrl} alt="pic" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                    </Modal>
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {addNews:state.adminNews};
}

AddNews = connect(mapStateToProps)(AddNews)

export default AddNews
